<template>
  <div class="dashboard-container">
    <h1 class="page-title">主机巡检</h1>
    
    <!-- 控制栏 -->
    <div class="control-bar">
      <div class="host-filter">
        <label class="filter-label">筛选主机：</label>
        <select v-model="filterOption" @change="onFilterChange" class="filter-select">
          <option value="all">全部主机</option>
          <option value="custom">自定义选择</option>
        </select>
      </div>
      
      <button 
        class="inspect-btn" 
        @click="startInspection" 
        :disabled="isInspecting || (filterOption === 'custom' && selectedHostIds.length === 0)">
        <span v-if="isInspecting" class="spinner">⏳</span>
        <span v-else>🔍</span>
        {{ isInspecting ? '巡检中...' : '开始巡检' }}
      </button>
    </div>

    <!-- 主机选择区 -->
    <div v-if="filterOption === 'custom'" class="host-selection">
      <div class="selection-header">
        <span>选择主机 ({{ selectedHostIds.length }}/{{ allHosts.length }})</span>
        <div class="selection-actions">
          <button @click="selectAll" class="btn-sm">全选</button>
          <button @click="clearSelection" class="btn-sm">清空</button>
        </div>
      </div>
      <div class="host-chips">
        <label 
          v-for="host in allHosts" 
          :key="host.id" 
          :class="['host-chip', { 'selected': selectedHostIds.includes(host.id) }]">
          <input 
            type="checkbox" 
            :value="host.id" 
            v-model="selectedHostIds"
            class="host-checkbox">
          <span class="host-chip-content">
            <span class="host-name">{{ host.name }}</span>
            <span class="host-ip">{{ host.ip }}</span>
          </span>
        </label>
      </div>
    </div>

    <!-- 巡检结果统计 -->
    <div v-if="inspectionData" class="stats-summary">
      <div class="summary-card total">
        <div class="card-icon">🖥️</div>
        <div class="card-content">
          <div class="card-label">总主机数</div>
          <div class="card-value">{{ inspectionData.total }}</div>
        </div>
      </div>
      <div class="summary-card online">
        <div class="card-icon">✅</div>
        <div class="card-content">
          <div class="card-label">在线主机</div>
          <div class="card-value">{{ inspectionData.online }}</div>
        </div>
      </div>
      <div class="summary-card offline">
        <div class="card-icon">❌</div>
        <div class="card-content">
          <div class="card-label">离线主机</div>
          <div class="card-value">{{ inspectionData.offline }}</div>
        </div>
      </div>
      <div class="summary-card time">
        <div class="card-icon">⏱️</div>
        <div class="card-content">
          <div class="card-label">巡检时间</div>
          <div class="card-value">{{ lastInspectionTime }}</div>
        </div>
      </div>
    </div>

    <!-- 邮箱配置按钮 -->
    <div v-if="inspectionData" class="email-action-bar">
      <button 
        @click="sendEmail" 
        class="email-btn">
        <span>📧 配置邮箱发送</span>
      </button>
      <span class="email-hint">点击配置邮箱，接收巡检报告</span>
    </div>

    <!-- 巡检结果列表 -->
    <div v-if="inspectionData && inspectionData.results" class="inspection-results">
      <div 
        v-for="result in inspectionData.results" 
        :key="result.id" 
        :class="['host-result-card', result.status]"
        @click="viewHostDetail(result)"
        style="cursor: pointer"
        title="点击查看详细信息">
        <div class="host-header">
          <div class="host-info">
            <span class="host-name">{{ result.name }}</span>
            <span class="host-ip">{{ result.ip }}</span>
          </div>
          <span :class="['status-badge', result.status]">
            {{ getStatusText(result.status) }}
          </span>
        </div>
        
        <div v-if="result.status === 'online'" class="resource-info">
          <!-- CPU -->
          <div class="resource-item">
            <div class="resource-header">
              <span class="resource-label">🖥️ CPU</span>
              <span class="resource-value">{{ result.cpu?.usage_percent?.toFixed(1) || 0 }}%</span>
            </div>
            <div class="progress-bar">
              <div 
                class="progress-fill cpu-fill" 
                :style="{ width: (result.cpu?.usage_percent || 0) + '%' }">
              </div>
            </div>
          </div>
          
          <!-- 内存 -->
          <div class="resource-item">
            <div class="resource-header">
              <span class="resource-label">💾 内存</span>
              <span class="resource-value">{{ result.memory?.usage_percent?.toFixed(1) || 0 }}%</span>
              <span class="resource-detail">
                {{ result.memory?.used_gb?.toFixed(2) || 0 }}GB / {{ result.memory?.total_gb?.toFixed(2) || 0 }}GB
              </span>
            </div>
            <div class="progress-bar">
              <div 
                class="progress-fill memory-fill" 
                :style="{ width: (result.memory?.usage_percent || 0) + '%' }">
              </div>
            </div>
          </div>
          
          <!-- 磁盘 -->
          <div class="resource-item">
            <div class="resource-header">
              <span class="resource-label">💿 磁盘</span>
              <span class="resource-value">{{ result.disk?.usage_percent?.toFixed(1) || 0 }}%</span>
              <span class="resource-detail">
                {{ result.disk?.used_gb?.toFixed(2) || 0 }}GB / {{ result.disk?.total_gb?.toFixed(2) || 0 }}GB
              </span>
            </div>
            <div class="progress-bar">
              <div 
                class="progress-fill disk-fill" 
                :style="{ width: (result.disk?.usage_percent || 0) + '%' }">
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="error-info">
          <span class="error-icon">⚠️</span>
          <span class="error-text">{{ result.error || '无法连接' }}</span>
        </div>
      </div>
    </div>
    
    <!-- 空状态提示 -->
    <div v-if="!inspectionData" class="empty-state">
      <div class="empty-icon">🔍</div>
      <div class="empty-text">点击"开始巡检"按钮，查看所有主机的系统资源使用情况</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../services/api'
import { loadingService } from '../services/loadingService'
import message from '../utils/message'

const router = useRouter()

const filterOption = ref('all')
const selectedHostIds = ref([])
const allHosts = ref([])
const isInspecting = ref(false)
const inspectionData = ref(null)
const isSendingEmail = ref(false)
const emailSentMessage = ref('')

const lastInspectionTime = computed(() => {
  if (!inspectionData.value) return '-'
  return new Date(inspectionData.value.timestamp * 1000).toLocaleTimeString('zh-CN')
})

// 获取所有主机列表
const fetchHosts = async () => {
  try {
    const response = await api.getHosts()
    allHosts.value = response.results || response
  } catch (error) {
    console.error('获取主机列表失败:', error)
    message.error('获取主机列表失败～\n' + error.message)
  }
}

// 筛选选项变化
const onFilterChange = () => {
  if (filterOption.value === 'all') {
    selectedHostIds.value = []
  }
}

// 全选
const selectAll = () => {
  selectedHostIds.value = allHosts.value.map(h => h.id)
}

// 清空选择
const clearSelection = () => {
  selectedHostIds.value = []
}

// 开始巡检
const startInspection = async () => {
  isInspecting.value = true
  
  // 显示加载界面
  const hostCount = filterOption.value === 'all' 
    ? allHosts.value.length 
    : selectedHostIds.value.length
  
  loadingService.showWithProgress({
    title: '主机批量巡检',
    tip: `正在巡检 ${hostCount} 台主机...`
  })
  
  try {
    // 模拟进度
    loadingService.setProgress(10)
    await new Promise(resolve => setTimeout(resolve, 200))
    
    loadingService.setTip('正在建立SSH连接...')
    loadingService.setProgress(25)
    await new Promise(resolve => setTimeout(resolve, 200))
    
    const payload = filterOption.value === 'all' 
      ? { host_ids: [] }  
      : { host_ids: selectedHostIds.value }
    
    loadingService.setTip('正在获取系统信息...')
    loadingService.setProgress(40)
    
    const response = await api.hostInspection(payload)
    
    loadingService.setProgress(75)
    loadingService.setTip('正在分析资源使用情况...')
    await new Promise(resolve => setTimeout(resolve, 300))
    
    loadingService.setProgress(95)
    loadingService.setTip('巡检完成！')
    
    inspectionData.value = response
    
    loadingService.setProgress(100)
    await new Promise(resolve => setTimeout(resolve, 300))
    
    loadingService.hide()
    
  } catch (error) {
    console.error('巡检失败:', error)
    loadingService.setTip('巡检失败！')
    setTimeout(() => {
      loadingService.hide()
      message.error('巡检失败～\n' + (error.response?.data?.error || error.message))
    }, 500)
  } finally {
    isInspecting.value = false
  }
}

// 获取状态文字
const getStatusText = (status) => {
  const statusMap = {
    'online': '在线',
    'offline': '离线',
    'auth_failed': '认证失败',
    'ssh_error': 'SSH错误',
    'unknown': '未知'
  }
  return statusMap[status] || status
}

// 发送邮件 - 跳转到邮箱配置页面
const sendEmail = () => {
  if (!inspectionData.value) {
    message.warning('请先执行巡检哦～')
    return
  }
  
  // 跳转到邮箱配置页面
  router.push('/email-config')
}

// 查看主机详情
const viewHostDetail = async (host) => {
  // 显示带有帐篷logo的加载界面
  loadingService.showWithProgress({
    title: `正在巡检主机：${host.name}`,
    tip: '正在连接主机...'
  })
  
  try {
    // 模拟进度：连接主机
    loadingService.setProgress(20)
    await new Promise(resolve => setTimeout(resolve, 300))
    
    // 执行单个主机的巡检
    loadingService.setTip('正在获取CPU信息...')
    loadingService.setProgress(40)
    
    const payload = { host_ids: [host.id] }
    const response = await api.hostInspection(payload)
    
    loadingService.setProgress(70)
    loadingService.setTip('正在获取内存和磁盘信息...')
    await new Promise(resolve => setTimeout(resolve, 300))
    
    loadingService.setProgress(90)
    loadingService.setTip('巡检完成！正在跳转...')
    await new Promise(resolve => setTimeout(resolve, 300))
    
    // 巡检完成，隐藏加载界面
    loadingService.setProgress(100)
    
    setTimeout(() => {
      loadingService.hide()
      
      // 跳转到主机详情页面
      router.push({
        name: 'HostDetail',
        params: { hostId: host.id },
        query: { 
          name: host.name,
          ip: host.ip,
          status: host.status
        }
      })
    }, 500)
    
  } catch (error) {
    console.error('巡检失败:', error)
    loadingService.setTip('巡检失败！')
    
    setTimeout(() => {
      loadingService.hide()
      message.error('巡检失败～\n' + (error.response?.data?.error || error.message))
    }, 500)
  }
}

onMounted(async () => {
  // 获取主机列表
  await fetchHosts()
  
  // 自动巡检本机 (10.0.0.19)
  const localhost = allHosts.value.find(host => host.ip === '10.0.0.19')
  
  if (localhost) {
    // 显示加载界面并自动巡检本机
    loadingService.showWithProgress({
      title: `正在巡检本机：${localhost.name}`,
      tip: '系统自动巡检中...'
    })
    
    try {
      // 模拟进度
      loadingService.setProgress(20)
      await new Promise(resolve => setTimeout(resolve, 300))
      
      loadingService.setTip('正在获取CPU信息...')
      loadingService.setProgress(40)
      
      // 执行本机巡检
      const payload = { host_ids: [localhost.id] }
      const response = await api.hostInspection(payload)
      
      loadingService.setProgress(70)
      loadingService.setTip('正在获取内存和磁盘信息...')
      await new Promise(resolve => setTimeout(resolve, 300))
      
      loadingService.setProgress(90)
      loadingService.setTip('巡检完成！')
      
      // 将巡检结果设置为inspectionData
      inspectionData.value = response
      
      loadingService.setProgress(100)
      await new Promise(resolve => setTimeout(resolve, 300))
      
      loadingService.hide()
      
    } catch (error) {
      console.error('自动巡检失败:', error)
      loadingService.hide()
      // 失败时不显示alert，静默处理
    }
  } else {
    console.warn('未找到本机 (10.0.0.19)，跳过自动巡检')
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.page-title {
  font-size: 32px;
  color: var(--color-accent-pink);
  text-align: center;
  margin-bottom: 30px;
  text-shadow: none;
  font-weight: 700;
  letter-spacing: 2px;
}

/* 控制栏 */
.control-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: var(--color-bg-secondary);
  border: none;
  border-radius: 20px;
  box-shadow: var(--shadow-card);
}

.host-filter {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-label {
  color: var(--color-text-primary);
  font-size: 14px;
  font-weight: 600;
}

.filter-select {
  padding: 10px 16px;
  background: var(--color-bg-primary);
  border: 2px solid var(--color-border);
  border-radius: 12px;
  color: var(--color-text-primary);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.filter-select:hover {
  border-color: var(--color-accent-pink);
}

.filter-select:focus {
  outline: none;
  border-color: var(--color-accent-pink);
  box-shadow: 0 0 0 3px rgba(255, 107, 157, 0.1);
}

.filter-select option {
  background: var(--color-bg-secondary);
  color: var(--color-text-primary);
}

.inspect-btn {
  padding: 12px 32px;
  background: linear-gradient(135deg, var(--color-accent-pink), var(--color-accent-purple));
  border: none;
  border-radius: 25px;
  color: white;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: var(--shadow-soft);
  display: flex;
  align-items: center;
  gap: 8px;
}

.inspect-btn:hover:not(:disabled) {
  transform: translateY(-3px) scale(1.02);
  box-shadow: var(--shadow-hover);
  background: linear-gradient(135deg, var(--color-accent-purple), var(--color-accent-pink));
}

.inspect-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 主机选择区 */
.host-selection {
  margin-bottom: 20px;
  padding: 20px;
  background: var(--color-bg-secondary);
  border: none;
  border-radius: 20px;
  box-shadow: var(--shadow-card);
}

.selection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  color: var(--color-text-primary);
  font-size: 14px;
  font-weight: 600;
}

.selection-actions {
  display: flex;
  gap: 10px;
}

.btn-sm {
  padding: 6px 16px;
  background: linear-gradient(135deg, var(--color-accent-pink), var(--color-accent-purple));
  border: none;
  border-radius: 15px;
  color: white;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-sm:hover {
  background: linear-gradient(135deg, var(--color-accent-purple), var(--color-accent-pink));
  transform: translateY(-2px);
}

.host-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.host-chip {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: var(--color-bg-primary);
  border: 2px solid var(--color-border);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.host-chip:hover {
  border-color: var(--color-accent-pink);
  transform: translateY(-2px);
}

.host-chip.selected {
  background: var(--color-bg-tertiary);
  border-color: var(--color-accent-pink);
}

.host-checkbox {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: var(--color-accent-pink);
}

.host-chip-content {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.host-name {
  color: var(--color-text-primary);
  font-size: 13px;
  font-weight: 600;
}

.host-ip {
  color: var(--color-text-secondary);
  font-size: 11px;
  font-family: monospace;
}

/* 统计卡片 */
.stats-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.summary-card {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 20px;
  background: var(--color-bg-secondary);
  border-radius: 15px;
  border: 2px solid;
  transition: all 0.3s;
  box-shadow: var(--shadow-card);
}

.summary-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--shadow-hover);
}

.summary-card.total {
  border-color: var(--color-accent-blue);
}

.summary-card.online {
  border-color: var(--color-accent-success);
}

.summary-card.offline {
  border-color: #ff6b6b;
}

.summary-card.time {
  border-color: var(--color-accent-orange);
}

.card-icon {
  font-size: 36px;
}

.card-content {
  flex: 1;
}

.card-label {
  color: var(--color-text-secondary);
  font-size: 13px;
  margin-bottom: 5px;
}

.card-value {
  color: var(--color-text-primary);
  font-size: 28px;
  font-weight: bold;
}

/* 邮件操作栏 */
.email-action-bar {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: var(--color-bg-secondary);
  border-radius: 15px;
  box-shadow: var(--shadow-card);
}

.email-btn {
  padding: 10px 24px;
  background: linear-gradient(135deg, var(--color-accent-orange), #ffc107);
  border: none;
  border-radius: 25px;
  color: white;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: var(--shadow-soft);
}

.email-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #ffc107, var(--color-accent-orange));
  transform: translateY(-3px) scale(1.02);
  box-shadow: var(--shadow-hover);
}

.email-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.email-hint {
  color: var(--color-text-secondary);
  font-size: 13px;
  font-style: italic;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(-10px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 巡检结果 */
.inspection-results {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.host-result-card {
  background: var(--color-bg-secondary);
  border: 2px solid var(--color-border);
  border-radius: 15px;
  padding: 20px;
  transition: all 0.3s;
  box-shadow: var(--shadow-card);
}

.host-result-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--shadow-hover);
}

.host-result-card.online {
  border-color: var(--color-accent-success);
}

.host-result-card.offline,
.host-result-card.auth_failed,
.host-result-card.ssh_error {
  border-color: #f44336;
}

.host-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 2px solid var(--color-border);
}

.host-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.host-info .host-name {
  color: var(--color-text-primary);
  font-size: 16px;
  font-weight: bold;
}

.host-info .host-ip {
  color: var(--color-text-secondary);
  font-size: 13px;
  font-family: monospace;
}

.status-badge {
  padding: 6px 14px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  border: 2px solid;
}

.status-badge.online {
  background: rgba(81, 207, 102, 0.15);
  color: var(--color-accent-success);
  border-color: var(--color-accent-success);
}

.status-badge.offline,
.status-badge.auth_failed,
.status-badge.ssh_error {
  background: rgba(255, 107, 107, 0.15);
  color: #ff6b6b;
  border-color: #ff6b6b;
}

/* 资源信息 */
.resource-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.resource-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.resource-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.resource-label {
  color: var(--color-text-primary);
  font-size: 14px;
  font-weight: 600;
}

.resource-value {
  color: var(--color-accent-pink);
  font-size: 18px;
  font-weight: bold;
}

.resource-detail {
  color: var(--color-text-secondary);
  font-size: 11px;
  margin-left: auto;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: var(--color-bg-primary);
  border-radius: 10px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.5s ease;
}

.cpu-fill {
  background: linear-gradient(90deg, #4caf50, #8bc34a);
  box-shadow: 0 0 10px rgba(76, 175, 80, 0.5);
}

.memory-fill {
  background: linear-gradient(90deg, #2196f3, #03a9f4);
  box-shadow: 0 0 10px rgba(33, 150, 243, 0.5);
}

.disk-fill {
  background: linear-gradient(90deg, #ff9800, #ffc107);
  box-shadow: 0 0 10px rgba(255, 152, 0, 0.5);
}

/* 错误信息 */
.error-info {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
  background: rgba(244, 67, 54, 0.1);
  border-radius: 8px;
}

.error-icon {
  font-size: 24px;
}

.error-text {
  color: #f44336;
  font-size: 14px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
}

.empty-icon {
  font-size: 80px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-text {
  color: var(--color-text-secondary);
  font-size: 16px;
}

@media (max-width: 768px) {
  .control-bar {
    flex-direction: column;
    gap: 15px;
  }
  
  .inspection-results {
    grid-template-columns: 1fr;
  }
  
  .stats-summary {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
